/*  Copyright 2010 princehaku
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  Author     : princehaku
 */
package net.techest.httpprotocols;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.text.ParseException;
import java.util.StringTokenizer;

import net.techest.util.StringDivider;

public class HTTPRequestBuilder {
	
	public static HTTPRequest buildRequest(InputStream in) throws ParseException{
		
		HTTPRequest request=new HTTPRequest();
		
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			StringTokenizer st;
			// 读入第一行 设置为messgae
			String statuline=br.readLine();
			st = new StringTokenizer(statuline, " ");
			if(st.countTokens()<3){
				throw new ParseException("状态行错误",0);
			}
			String requestType=st.nextToken();
			
			request.setStatuLine(statuline);
			//开始读取heads

			String line="--";
			while (true){
				line = br.readLine();
				StringDivider sd;
				//System.out.println("读入" + line);
				if(line.equals(""))break;
				try{
					sd = new StringDivider(line, ":");
				}catch(ParseException ex){
					throw new ParseException("消息报头错误",0);
				}
				String key = sd.getLeft();
				String value = sd.getRight();
				//System.out.println("读入 key " + key);
				//System.out.println("读入 value " + value);
				request.setParam(key, value);
			}
			
			//开始读取POST正文
			line="--";
			if(requestType=="POST"){
				StringBuilder context=new StringBuilder();
				while (!line.equals("")) {
					line = br.readLine();
					context.append(line);
				}
				//组合正文
				if(!context.equals("")){
					context.append("\n");
					request.setContext(context.toString().getBytes());
				}
			}
			System.out.println("组建完成");
			
		} catch (IOException e) {
			System.out.println("组建完成"+e.getMessage());
		}
		
		return request;
	}
}
